package cn.wit.summit.chwan.widgets;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.webkit.WebView;


/**
 * Created by pengsk on 2015/1/5.
 */
public class ObservableWebView extends WebView {
    public enum ScrollState {
        STOP,
        UP,
        DOWN,
    }

    String Tag = getClass().getSimpleName();
    private int mPrevScrollY;
    private ScrollState mScrollState;
    //点击下来时的x坐标
    float startX;
    float startY;

    public ObservableWebView(Context context) {
        super(context);
    }

    public ObservableWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ObservableWebView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }


    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        switch (ev.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
//                guard = false;
                startX = ev.getX();
                startY = ev.getY();

                getParent().requestDisallowInterceptTouchEvent(true);
                break;
            case MotionEvent.ACTION_UP:
                getParent().requestDisallowInterceptTouchEvent(false);
                break;
            case MotionEvent.ACTION_MOVE:
//                    if(!guard){

                float gapX = Math.abs( ev.getX() - startX );
                float gapY = Math.abs( ev.getY() - startY );

                if(gapX>gapY){//横向
                    getParent().requestDisallowInterceptTouchEvent(false);
                }else//垂直
                    getParent().requestDisallowInterceptTouchEvent(true);

                if(getScrollY()==0){
                    getParent().requestDisallowInterceptTouchEvent(false);
                }

                break;
            case MotionEvent.ACTION_CANCEL:

                break;
        }
        return super.onTouchEvent(ev);
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);


        if (mPrevScrollY < t) {
            //down
            mScrollState = ScrollState.UP;
            Log.d(Tag, "down...");
            getParent().requestDisallowInterceptTouchEvent(true);
        } else if (t < mPrevScrollY) {
            //up
            mScrollState = ScrollState.DOWN;
            Log.d(Tag,"up...");
            Log.d(Tag,"getScrollY()="+getScrollY());

            if(getScrollY()==0){
                getParent().requestDisallowInterceptTouchEvent(false);
            }

        }
        mPrevScrollY = t;

    }
}
